"use client";
import { useSidebarStore } from "@/components/state/sidebar_state";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { getData, postData } from "@/components/utils/api";
import {
  DataListProps,
  FastResponse,
  VersionProps,
  DataItem,
} from "@/components/models/dataprops";
import { useEffect, useState } from "react";
import { ServerErrorPanel } from "@/components/ServerError";
import LoadingPage from "@/components/loadingpage";

function LLMState() {
  const updateSelected = useSidebarStore((state) => state.updateSelected);
  const [modelName, setModelName] = useState("Irlab Public LLM");
  const [version, setVersion] = useState("");
  const [updateTime, setUpdateTime] = useState("");
  const [modelState, setModelState] = useState("");
  const [requestError, setRequestError] = useState(false);
  const [loading, setLoading] = useState(false);

  const [tunedList, setTunedList] = useState<DataItem[]>([]);
  const [untunedlist, setUntunedlist] = useState<DataItem[]>([]);

  useEffect(() => {
    async function loadVersionState() {
      try {
        setLoading(true);
        const result = await getData<FastResponse<VersionProps>>(
          "/model/state/query"
        ); // 泛型定义请求和响应类型
        if (result.code === 200) {
          setModelName(result.data.model_name);
          setVersion(result.data.model_version);
          setUpdateTime(result.data.update_time.replaceAll("T", " "));
          setModelState(result.data.state);
        }
        setLoading(false);
      } catch (error) {
        console.log("Error submitting data:", error);
        setLoading(false);
        setRequestError(true);
      }
    }

    updateSelected("调优状态", "大模型调度");
    loadVersionState();
  }, [updateSelected]);

  useEffect(() => {
    async function loadTunedDatasets(isBefore: boolean) {
      const payload: DataListProps = {
        data_from: "",
        data_type: "调优数据",
        query: "",
        is_before: isBefore,
        time_range: updateTime,
      };
      try {
        const result = await postData<FastResponse<DataItem[]>, DataListProps>(
          "/data/list",
          payload
        ); // 泛型定义请求和响应类型
        if (isBefore) {
          setTunedList(result.data);
        } else {
          setUntunedlist(result.data);
        }
        setRequestError(false);
      } catch (error) {
        console.log("Error submitting data:", error);
        setRequestError(true);
      }
    }
    // 是不是tuned数据
    loadTunedDatasets(true);
    loadTunedDatasets(false);
  }, [updateTime]);

  return (
    <>
      {loading ? (
        <LoadingPage />
      ) : requestError ? (
        <ServerErrorPanel />
      ) : (
        <div className="grid grid-cols-[150px_auto] items-center text-sm">
          <div className="p-2 pl-2 text-end"> 模型名：</div>
          <Label htmlFor="email">
            <span className="text-sm font-semibold">{modelName} </span>
          </Label>
          <div className="p-2 pl-2 text-end"> 最新版本号：</div>
          <Label htmlFor="email">{version}</Label>
          <div className="p-2 pl-2 text-end text-sm"> 更新时间：</div>
          <Label htmlFor="email" className=" text-sm">
            {updateTime}
          </Label>
          <div className="p-2 pl-2 text-end"> 训练状态：</div>
          <div className="flex felx-flow items-center gap-4">
            <div
              className={`w-4 h-4 ${
                modelState === "unstarted" ? "bg-red-600" : "bg-green-600"
              } rounded-md drop-shadow-lg`}
            ></div>
            {modelState == "unstarted" ? (
              <p>模型调优未开始</p>
            ) : (
              <p>模型调优中</p>
            )}
          </div>
          <p></p>
          <p className="mb-4 text-gray-600 text-xs">
            模型每天凌晨12:00开始扫描进行自动训练，请在
            <a href="/data/register" className="text-green-700 font-semibold">
              数据注册
            </a>
            中进行注册。
          </p>
          <div className="p-4 pl-2 text-end"> 已调优数据：</div>
          <div className="felx flex-grow h-20 border-2 border-dashed rounded-md p-2">
            {tunedList.length > 0 &&
              tunedList.map((item: DataItem) => (
                <Badge variant="outline" key={item.id}>
                  {item.name}
                </Badge>
              ))}
          </div>
          <div className="p-12 pr-4 text-end"> 待调优数据：</div>
          <div className="felx flex-grow h-20 border-2 border-dashed rounded-md p-2">
            {untunedlist.length > 0 &&
              untunedlist.map((item: DataItem) => (
                <Badge variant="outline" key={item.id}>
                  {item.name}
                </Badge>
              ))}
          </div>
        </div>
      )}
    </>
  );
}

export default LLMState;
